//
//  SZLReceiveAddressViewController.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/8/5.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "SZLReceiveAddressViewController.h"
#import "ReceiveTableViewCell.h"
#import "PickUpTableViewCell.h"
#import "SZLCreateAddressViewController.h"
#import "ReceiveAddressNetwork.h"
#import "SZLAccountHelper.h"
#import "MBProgressHUD+MJ.h"

@interface SZLReceiveAddressViewController ()<UITableViewDataSource,UITableViewDelegate,ReceiveTableViewCellDelegate>

@property (nonatomic,strong) UITableView *sourceTab;
@property (nonatomic,strong) NSMutableArray *addresses;

@end

@implementation SZLReceiveAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"收货地址管理";
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setTableView];
    [self getAddressList];
}
- (void)setTableView
{
    [self.view addSubview:self.sourceTab];
    self.sourceTab.contentInset = UIEdgeInsetsMake(0, 0, 70, 0);
    UIButton *createBtn = [[UIButton alloc] initWithFrame:CGRectMake(25, ScreenH-SafeAreaTopHeight-20-40, ScreenW-50, 40)];
    [createBtn setTitle:@"新建地址" forState:UIControlStateNormal];
    [createBtn setBackgroundImage:GetImage(@"btn_bg_login_normal") forState:UIControlStateNormal];
    [createBtn setBackgroundImage:GetImage(@"btn_bg_login_normal") forState:UIControlStateHighlighted];
    [self.view addSubview:createBtn];
    [createBtn addTarget:self action:@selector(createClick) forControlEvents:UIControlEventTouchUpInside];
}
- (void)createClick
{
    SZLCreateAddressViewController *createVc = [[SZLCreateAddressViewController alloc]init];
    createVc.saveSuccessBlock = ^(){
        [self getAddressList];
    };
    [self.navigationController pushViewController:createVc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.addresses.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ReceiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ReceiveTableViewCell class])];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.addresses[indexPath.row];
    cell.delegate = self;
    return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressModel *deleteModel = self.addresses[indexPath.row];
    BOOL isDefault = deleteModel.isDefault;//记录删除的状态
    [self deleteAddress:self.addresses[indexPath.row]];
    [self.addresses removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
    if (isDefault&&self.addresses.count>0) {//如果删除默认  把第一个改成默认
        AddressModel *model = self.addresses.firstObject;
        model.isDefault = YES;
        NSIndexPath *firstPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [tableView reloadRowsAtIndexPaths:@[firstPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressModel *model = self.addresses[indexPath.row];
    if (self.type == AddressTypeSelect) {
        if (self.selectBlock) {
            self.selectBlock(model);
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        return;
    }
    SZLCreateAddressViewController *createVc = [[SZLCreateAddressViewController alloc]init];
    createVc.model = model;
    createVc.saveSuccessBlock = ^(){
        [self getAddressList];
    };
    [self.navigationController pushViewController:createVc animated:YES];
}
#pragma mark --------------ReceiveTableViewCellDelegate-------------
- (void)receiveTableViewCellChangeDefault:(AddressModel *)model
{
    for (AddressModel *otherModel in self.addresses) {
        otherModel.isDefault = 0;
    }
    model.isDefault = 1;
    [self changeDefault:model];
    [self.sourceTab reloadData];
}
#pragma mark --------------请求相关-------------
- (void)deleteAddress:(AddressModel *)model
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"id"] = @(model.ID);
    [self showClearBgWaiter];
    [ReceiveAddressNetwork deleteAddressWithParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            [MBProgressHUD showSuccess:@"删除成功" toView:self.view];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
- (void)changeDefault:(AddressModel *)model
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"id"] = @(model.ID);
    [self showClearBgWaiter];
    [ReceiveAddressNetwork changeDefaultAddressWithParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
    }];
}
- (void)getAddressList
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    [self showWaiter];
    [ReceiveAddressNetwork getAddressListWithParame:parame response:^(BOOL success, NSString *msg, NSArray *addresses) {
        [self hideWaiter];
        if (success) {
            [self hideRequestAgainView];
            if (addresses.count == 0) {
                [self showNoDataLab:self.sourceTab range:CGRectMake(0, self.sourceTab.height*0.4, ScreenW, 20) title:@"暂无收货地址，请新建收货地址"];
            }else{
                [self hideNoDataLab];
                [self.addresses removeAllObjects];
                [self.addresses addObjectsFromArray:addresses];
                [self.sourceTab reloadData];
            }
        }else{
            if ([msg isEqualToString:NoNetworkStatus]) {
                [self showRequestAgainView:@selector(getAddressList)];
            }else{
                [MBProgressHUD showError:msg toView:self.view];
            }
        }
    }];
}
- (UITableView *)sourceTab
{
    if (!_sourceTab) {
        _sourceTab = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH-64)];
        _sourceTab.delegate = self;
        _sourceTab.dataSource = self;
        _sourceTab.backgroundColor = RGBColor(239, 239, 244);
        [_sourceTab registerNib:[UINib nibWithNibName:NSStringFromClass([ReceiveTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ReceiveTableViewCell class])];
        _sourceTab.tableFooterView = [[UIView alloc]init];
    }
    return _sourceTab;
}
- (NSMutableArray *)addresses
{
    if (!_addresses) {
        _addresses = [NSMutableArray array];
    }
    return _addresses;
}

@end
